package com.ls.aop.jdk.domatic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ls.aop.jdk.Subject;

public class JdkProxyHandler implements InvocationHandler{
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private Subject subject;
	
	public  JdkProxyHandler(Subject subject) {
		this.subject=subject;
	}
	
	public static Subject getInstance(Subject subject) {
		System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
		JdkProxyHandler handler = new JdkProxyHandler(subject);
		return (Subject) Proxy.newProxyInstance(JdkProxyHandler.class.getClassLoader(), subject.getClass().getInterfaces(), handler);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object ret;
		try {
			logger.info("before method exec");
		ret = method.invoke(subject, args);
		logger.info("after method exec");
		return ret;
		}catch(Throwable e) {
			logger.error("exec method {} thrwo exception e",method.getName(),e);
			throw e;
		}finally {
			logger.info(" method exec finished ");
		}
	}

}
